/**
 * @author GhostWei
 */
var col = document.getElementsByTagName("script");
var jsrc = col.item(col.length-1).src; 
var i = jsrc.indexOf("?"); 
var params = jsrc.substr(i + 1, jsrc.length).replace('&amp;', '&').split('&');

var translator = {
	lang: '',
	url: 'translator',
	getLang: function() {
		eval('var l = ' + this.lang);
		return l;
	},
	select: function() {
		var v = $('select#translator-api').val();
		if(v) {
			this.reset();
			var lang = this.getLang();
			if(typeof(lang[v]) != 'undefined') {
				var f = $('select#translator-from');
				var t = $('select#translator-to');
				f.find('option').each(function(){$(this).remove();});
				t.find('option').each(function(){$(this).remove();});
				for(var i in lang[v]) {
					f.append('<option value="' + i + '">' + lang[v][i] + '</option>');
					t.append('<option value="' + i + '">' + lang[v][i] + '</option>');
				}
			}
		} else {
			this.reset();
		}
	},
	reset: function() {
		$('select#translator-from option').each(function(){$(this).remove();});
		$('select#translator-from').append('<option value="">== SELECT ==</option>');
		$('select#translator-to option').each(function(){$(this).remove();});
		$('select#translator-to').append('<option value="">== SELECT ==</option>');
	},
	get: function(api, f, t, v, o, u) {
		if(o.attr('__status') == 's') return false;
		var data = [];
		data.push('r=' + Math.random().toString().replace('.', '_'));
		data.push('api=' + api);
		data.push('f=' + f);
		data.push('t=' + t);
		data.push('text=' + encodeURIComponent(v));
		$.ajax({type:'POST',dataType:'json',url:u,data:data.join('&'),success:function(json, status){
			try {
				if(json.status == 0) {
					throw json;
				}
				o.unbind('focus').unbind('blur').attr('__status', 's').val(json.text);
			} catch (e) {
				_error(e.message);
			}
		}, beforeSend: function(req) {
			o.unbind('focus').unbind('blur').attr('__val', o.val()).val('translating ...');
		}, error: function (req, msg, e) {
			_error(req['responseText']);
		}, timeout: 30000});
		return false;
		
		function _error(msg) {
			o.attr('__status', 'e')
				.attr('__e', msg)
				.val(o.attr('__val'))
				.focus(function(){
					$(this).val($(this).attr('__e'));
				}).blur(function(){
					$(this).val($(this).attr('__val'));
				});
		}
	},
	start: function() {
		var f = $('select#translator-from').val();
		var t = $('select#translator-to').val();
		var a = $('select#translator-api').val();
		if(!f || !t) {
			alert('Please select language From and To');
			return false;
		}
		if(f == t) {
			alert('From and To is not different');
			return false;
		}
		var self = this;
		$('.translator').each(function(){
			var text = $(this).val();
			if(text != '') {
				new self.get(a, f, t, text, $(this), self.url);
			}
		});
	}
};
for(var key in params) {
	var s = params[key];
	var n = s.substring(0, s.indexOf('='));
	var v = decodeURIComponent(s.substring(s.indexOf('=') + 1));
	translator[n] = v;
}